import configparser
import os
import uuid
from typing import Optional
from dataclasses import dataclass

@dataclass
class ApiConfig:
    api_base_url: str = "http://192.168.1.3:9011/api"
    websocket_url: str = "ws://192.168.1.3:9088/ws/"
    logger_debug: bool = False
    device_name: str = ""
    device_id: str = ""
    
    wxid: str = ""
# ... existing code ...
    def get(self, section: str, key: str, default: str = "") -> str:
        """获取配置值，每次都重新加载配置文件"""
        self._load_config()
        try:
            if self.config.has_section(section) and self.config.has_option(section, key):
                value = self.config.get(section, key)
                # 移除对list类型的特殊处理，因为configparser返回的不是list类型
                return str(value)
            # 处理DEFAULT section的特殊情况
            elif self.config.has_option('DEFAULT', key):
                value = self.config.get('DEFAULT', key)
                return str(value)
            return default
        except Exception as e:
            print(f"❌ 获取配置值失败: {e}")
            return default
# ... existing code ...

class ConfigManager:
    """配置管理器"""
    
    _instance = None
    _initialized: bool = False
    
    def __new__(cls, config_file: Optional[str] = None):
        if cls._instance is None:
            cls._instance = super(ConfigManager, cls).__new__(cls)
            cls._instance._initialized = False
        return cls._instance
    
    def __init__(self, config_file: Optional[str] = None):
        if self._initialized:
            return
        
        # 如果没有指定配置文件，默认使用项目根目录的config.properties
        if config_file is None:
            # 获取当前文件所在目录
            current_dir = os.path.dirname(os.path.abspath(__file__))
            # 项目根目录是common的上级目录
            project_root = os.path.dirname(current_dir)
            config_file = os.path.join(project_root, "config.properties")
        
        self.config_file = config_file
        self.config = configparser.ConfigParser()
        self._load_config()
        self.api_config = self._load_api_config()
        self._initialized = True
        print(f"🔧 配置管理器初始化完成 - 进程ID: {os.getpid()}")
        print(f"📁 配置文件: {os.path.abspath(self.config_file)}")
    
    def _load_config(self) -> None:
        """加载配置文件"""
        if os.path.exists(self.config_file):
            self.config.read(self.config_file, encoding='utf-8')
        else:
            print(f"⚠️ 配置文件 {self.config_file} 不存在，使用默认配置")
    
    def reload(self) -> None:
        """强制重新加载配置文件和api_config"""
        self._load_config()
        self.api_config = self._load_api_config()
    
    def get(self, section: str, key: str, default: str = "") -> str:
        """获取配置值，每次都重新加载配置文件"""
        self._load_config()
        try:
            if self.config.has_section(section) and self.config.has_option(section, key):
                value = self.config.get(section, key)
                if not value:
                    return default
                if isinstance(value, list) :  # 处理列表类型的值
                    return default
                return str(value)
            else:
                value = self.config.defaults().get(key)
                if not value:
                    return default
                if isinstance(value, list):  # 处理列表类型的值
                    return default
                return str(value)
            return default
        except Exception as e:
            print(f"❌ 获取配置值失败: {e}")
            return default
    
    def set(self, section: str, key: str, value: str):
        """设置配置值"""
        self._load_config()
        if not self.config.has_section(section):
            self.config.add_section(section)
        self.config.set(section, key, value)
        self._save_config()
    
    def _save_config(self):
        """保存配置文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                self.config.write(f)
            print(f"✅ 配置文件保存成功: {self.config_file}")
        except Exception as e:
            print(f"❌ 配置文件保存失败: {e}")
    
    def save_wxid(self, wxid: str):
        """保存wxid到配置文件"""
        self.set("CONFIG", "wxid", wxid)
        self.api_config.wxid = wxid
        print(f"✅ wxid已保存到配置文件: {wxid}")
    
    def get_wxid(self) -> str:
        """从配置文件获取wxid"""
        wxid = self.get("CONFIG", "wxid", "")
        self.api_config.wxid = wxid
        return wxid
    
    def clear_wxid(self):
        """清除配置文件中的wxid"""
        self.set("CONFIG", "wxid", "")
        self.api_config.wxid = ""
        print("✅ wxid已从配置文件清除")
    
    def _generate_device_id(self) -> str:
        """生成设备ID"""
        return str(uuid.uuid4()).replace('-', '')[:16]
    
    def _load_api_config(self) -> ApiConfig:
        section = "DEFAULT"
        api_base_url = self.get(section, "api_base_url", "http://192.168.1.3:9011/api")
        websocket_url = self.get(section, "websocket_url", "ws://192.168.1.3:9088/ws/")
        logger_debug = self.get(section, "logger.debug", "False").lower() == "true"
        device_name = self.get(section, "device_name", "AndroidPad")
        device_id = self.get(section, "device_id", "")
        wxid = self.get("CONFIG", "wxid", "")
        if not device_id:
            device_id = self._generate_device_id()
            print(f"自动生成设备ID: {device_id}")
        config = ApiConfig(
            api_base_url=api_base_url,
            websocket_url=websocket_url,
            logger_debug=logger_debug,
            device_name=device_name,
            device_id=device_id,
            wxid=wxid
        )
        print(f"📋 加载的配置:")
        print(f"  API地址: {config.api_base_url}")
        print(f"  WebSocket地址: {config.websocket_url}")
        print(f"  设备名称: {config.device_name}")
        print(f"  设备ID: {config.device_id}")
        print(f"  调试模式: {config.logger_debug}")
        print(f"  微信ID: {config.wxid or '未设置'}")
        return config

    def get_api_config(self) -> ApiConfig:
        """每次都重新加载api_config"""
        self.reload()
        print(f"[DEBUG] get_api_config 被调用 - 进程ID: {os.getpid()}")
        print(f"[DEBUG] 配置文件路径: {os.path.abspath(self.config_file)}")
        print(f"[DEBUG] 当前配置内容: {self.api_config}")
        return self.api_config

# 全局配置管理器实例
config_manager = ConfigManager()


